package com.mall.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.R;
import com.mall.entity.LoginUser;
import com.mall.entity.SmoothMallUser;
import com.mall.mapper.SmoothMallUserMapper;
import com.mall.service.SmoothMallUserService;
import com.mall.util.JwtUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class SmoothMallUserServiceImpl extends ServiceImpl<SmoothMallUserMapper, SmoothMallUser> implements SmoothMallUserService {
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public HashMap<String,String> login(SmoothMallUser smoothMallUser) {
        //创建一个authenticationManager进行用户认证需要的Authentication多态实现类对象
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(smoothMallUser.getUsername(),smoothMallUser.getPassword());
        //authenticationManager会调用到我重写的UserDetailsServiceImpl方法进行校验并返回一个UserdetailS对象，继续进行密码校验等操作后返回
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        //通过返回的值获取用户信息，生产一个jwt会给前端，并将用户信息存到redis当中
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getSmoothMallUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        redisTemplate.opsForValue().set("token:"+userId,loginUser,60, TimeUnit.MINUTES);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("token",jwt);
        return hashMap;
    }
}
